<template>
  <div class="weather-page">
    <div class="weather-header">
      <h1>天气查询</h1>
      <p>查看实时天气信息和预报</p>
    </div>
    
    <div class="weather-container">
      <div class="search-section">
        <div class="search-box">
          <input 
            v-model="searchCity" 
            @keyup.enter="searchWeather"
            placeholder="输入城市名称或点击获取当前位置"
            class="city-input"
          />
          <button @click="searchWeather" class="search-btn">
            <i class="fa fa-search"></i>
          </button>
        </div>
        
        <button @click="getCurrentLocationWeather" class="location-btn">
          <i class="fa fa-location-arrow"></i>
          获取当前位置天气
        </button>
      </div>
      
      <div v-if="loading" class="loading">
        <i class="fa fa-spinner fa-spin"></i>
        加载中...
      </div>
      
      <div v-if="error" class="error-message">
        <i class="fa fa-exclamation-triangle"></i>
        {{ error }}
      </div>
      
      <div v-if="weatherData" class="weather-content">
        <div class="current-weather">
          <h2>{{ weatherData.city }}</h2>
          <div class="weather-main">
            <div class="temperature">{{ weatherData.temperature }}°C</div>
            <div class="weather-desc">{{ weatherData.weather }}</div>
            <div class="weather-icon">
              <i :class="getWeatherIcon(weatherData.weather)"></i>
            </div>
          </div>
          <div class="weather-details">
            <div class="detail-item">
              <span class="label">湿度:</span>
              <span class="value">{{ weatherData.humidity }}%</span>
            </div>
            <div class="detail-item">
              <span class="label">风向:</span>
              <span class="value">{{ weatherData.winddirection }}</span>
            </div>
            <div class="detail-item">
              <span class="label">风力:</span>
              <span class="value">{{ weatherData.windpower }}级</span>
            </div>
            <div class="detail-item">
              <span class="label">更新时间:</span>
              <span class="value">{{ formatTime(weatherData.reporttime) }}</span>
            </div>
          </div>
        </div>
        
        <div v-if="forecastData && forecastData.length > 0" class="forecast-section">
          <h3>未来天气预报</h3>
          <div class="forecast-list">
            <div 
              v-for="(day, index) in forecastData.slice(0, 7)" 
              :key="index"
              class="forecast-item"
            >
              <div class="forecast-date">{{ formatDate(day.date) }}</div>
              <div class="forecast-weather">
                <i :class="getWeatherIcon(day.dayweather)"></i>
                <span>{{ day.dayweather }}</span>
              </div>
              <div class="forecast-temp">
                {{ day.nighttemp }}°C / {{ day.daytemp }}°C
              </div>
              <div class="forecast-wind">
                {{ day.daywind }} {{ day.daypower }}级
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';

// 使用后端API composable
const { getWeather } = useBackendApi();

const weatherData = ref<any>(null);
const forecastData = ref<any[]>([]);
const loading = ref(false);
const error = ref('');
const searchCity = ref('');

// 搜索天气
const searchWeather = async () => {
  if (!searchCity.value.trim()) {
    error.value = '请输入城市名称';
    return;
  }
  
  await fetchWeather({ city: searchCity.value.trim() });
};

// 获取当前位置天气
const getCurrentLocationWeather = async () => {
  if (!process.client) return;
  
  loading.value = true;
  error.value = '';
  
  try {
    const position = await new Promise<GeolocationPosition>((resolve, reject) => {
      navigator.geolocation.getCurrentPosition(resolve, reject, {
        enableHighAccuracy: true,
        timeout: 10000,
        maximumAge: 60000
      });
    });
    
    const { longitude, latitude } = position.coords;
    await fetchWeather({ location: `${longitude},${latitude}` });
    
  } catch (err) {
    console.error('获取位置失败:', err);
    error.value = '无法获取当前位置，请检查定位权限';
  } finally {
    loading.value = false;
  }
};

// 获取天气数据
const fetchWeather = async (params: { city?: string; location?: string }) => {
  loading.value = true;
  error.value = '';
  
  try {
    const response = await getWeather(params);
    
    if (response.success) {
      // 后端返回的数据结构：{ data: { lives: [...], casts: [...] } }
      const data = response.data;
      
      // 处理实时天气数据 (lives数组)
      if (data.lives && data.lives.length > 0) {
        const liveData = data.lives[0];
        weatherData.value = {
          city: liveData.city,
          weather: liveData.weather,
          temperature: liveData.temperature,
          humidity: liveData.humidity,
          winddirection: liveData.winddirection,
          windpower: liveData.windpower,
          reporttime: liveData.reporttime
        };
      }
      
      // 处理预报数据 (casts数组)
      if (data.casts && data.casts.length > 0) {
        forecastData.value = data.casts.map((cast: any) => ({
          date: cast.date,
          dayweather: cast.dayweather,
          nightweather: cast.nightweather,
          daytemp: cast.daytemp,
          nighttemp: cast.nighttemp,
          daywind: cast.daywind,
          nightwind: cast.nightwind,
          daypower: cast.daypower,
          nightpower: cast.nightpower
        }));
      }
    } else {
      error.value = response.message || '获取天气信息失败';
    }
  } catch (err) {
    console.error('天气API调用失败:', err);
    error.value = '获取天气信息失败';
  } finally {
    loading.value = false;
  }
};

// 获取天气图标
const getWeatherIcon = (weather: string): string => {
  if (!weather) return 'fa fa-question';
  
  const weatherLower = weather.toLowerCase();
  
  if (weatherLower.includes('晴')) return 'fa fa-sun-o';
  if (weatherLower.includes('多云')) return 'fa fa-cloud';
  if (weatherLower.includes('阴')) return 'fa fa-cloud';
  if (weatherLower.includes('雨')) return 'fa fa-tint';
  if (weatherLower.includes('雪')) return 'fa fa-snowflake-o';
  if (weatherLower.includes('雾')) return 'fa fa-smog';
  if (weatherLower.includes('霾')) return 'fa fa-smog';
  
  return 'fa fa-cloud';
};

// 格式化时间
const formatTime = (timeStr: string): string => {
  if (!timeStr) return '';
  return new Date(timeStr).toLocaleString('zh-CN');
};

// 格式化日期
const formatDate = (dateStr: string): string => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  const today = new Date();
  const tomorrow = new Date(today);
  tomorrow.setDate(tomorrow.getDate() + 1);
  
  if (date.toDateString() === today.toDateString()) {
    return '今天';
  } else if (date.toDateString() === tomorrow.toDateString()) {
    return '明天';
  } else {
    return date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' });
  }
};
</script>

<style scoped>
.weather-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.weather-header {
  text-align: center;
  color: white;
  margin-bottom: 30px;
}

.weather-header h1 {
  font-size: 2.5rem;
  margin-bottom: 10px;
  font-weight: 300;
}

.weather-header p {
  font-size: 1.1rem;
  opacity: 0.9;
}

.weather-container {
  max-width: 800px;
  margin: 0 auto;
  background: white;
  border-radius: 15px;
  padding: 30px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
}

.search-section {
  margin-bottom: 30px;
}

.search-box {
  display: flex;
  margin-bottom: 15px;
}

.city-input {
  flex: 1;
  padding: 12px 15px;
  border: 2px solid #e1e5e9;
  border-radius: 8px 0 0 8px;
  font-size: 16px;
  outline: none;
  transition: border-color 0.3s;
}

.city-input:focus {
  border-color: #667eea;
}

.search-btn {
  padding: 12px 20px;
  background: #667eea;
  color: white;
  border: none;
  border-radius: 0 8px 8px 0;
  cursor: pointer;
  transition: background-color 0.3s;
}

.search-btn:hover {
  background: #5a6fd8;
}

.location-btn {
  width: 100%;
  padding: 12px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
}

.location-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
}

.loading {
  text-align: center;
  padding: 40px;
  color: #666;
  font-size: 18px;
}

.loading i {
  margin-right: 10px;
  color: #667eea;
}

.error-message {
  background: #fff5f5;
  color: #e53e3e;
  padding: 15px;
  border-radius: 8px;
  border: 1px solid #fed7d7;
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 14px;
  margin-bottom: 20px;
}

.current-weather {
  text-align: center;
  margin-bottom: 30px;
  padding: 30px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 15px;
  color: white;
}

.current-weather h2 {
  font-size: 2rem;
  margin-bottom: 20px;
  font-weight: 300;
}

.weather-main {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 20px;
  margin-bottom: 30px;
}

.temperature {
  font-size: 4rem;
  font-weight: 300;
}

.weather-desc {
  font-size: 1.5rem;
  margin-bottom: 10px;
}

.weather-icon i {
  font-size: 3rem;
  opacity: 0.9;
}

.weather-details {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 15px;
  text-align: left;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
}

.detail-item:last-child {
  border-bottom: none;
}

.label {
  opacity: 0.8;
}

.value {
  font-weight: 500;
}

.forecast-section {
  margin-top: 30px;
}

.forecast-section h3 {
  font-size: 1.5rem;
  margin-bottom: 20px;
  color: #333;
  text-align: center;
}

.forecast-list {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
}

.forecast-item {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 10px;
  text-align: center;
  border-left: 4px solid #667eea;
}

.forecast-date {
  font-weight: 600;
  color: #333;
  margin-bottom: 10px;
}

.forecast-weather {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  margin-bottom: 10px;
  color: #666;
}

.forecast-weather i {
  color: #667eea;
  font-size: 1.2rem;
}

.forecast-temp {
  font-weight: 600;
  color: #333;
  margin-bottom: 5px;
}

.forecast-wind {
  font-size: 0.9rem;
  color: #999;
}

@media (max-width: 768px) {
  .weather-header h1 {
    font-size: 2rem;
  }
  
  .weather-container {
    padding: 20px;
  }
  
  .current-weather {
    padding: 20px;
  }
  
  .temperature {
    font-size: 3rem;
  }
  
  .forecast-list {
    grid-template-columns: 1fr;
  }
}
</style> 